package com.weaver.seconddev.custom.hook;
import cn.hutool.core.codec.Base64;
import com.weaver.ebuilder.datasource.api.entity.ExecuteSqlEntity;
import com.weaver.ebuilder.datasource.api.enums.SourceType;
import com.weaver.ebuilder.datasource.api.service.DataSetService;
import com.weaver.loom.api.annotation.RegHook;
import com.weaver.loom.context.register.AbstractRegHookEvent;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

/**
 *提交到指定节点
 * @author: chenwh
 * @created: 2024/01/31 15:27
 */
@Slf4j
@RegHook(module = "workflow", event = "wfcRequestOperateEvent", order = 0)
public class RequestRuntimeHandleHook extends AbstractRegHookEvent {
    public RequestRuntimeHandleHook() {
        log.error("==RequestRuntimeHandleHook===init==" );
    }
    
    @Autowired
    private RecordSet recordSet;
    
    @Autowired
    private RecordSet recordSet2;
    
    @Autowired
    private DataSetService dataSetService;
    
    
    
    public List<LinkedHashMap<String, Object>> getRelationConfigList(String sql ,String service){
        ExecuteSqlEntity executeSqlEntity = new ExecuteSqlEntity();
        executeSqlEntity.setSql(Base64.encode(sql));
        //groupid,可以访问  E10地址/api/datasource/ds/group?sourceType=LOGIC 获取
        executeSqlEntity.setGroupId(service);
        executeSqlEntity.setSourceType(SourceType.LOGIC);
        Map<String, Object> datas = dataSetService.executeSql(executeSqlEntity);
        log.error("=====RequestRuntimeHandleHook(提交到指定节点)===datas{}",datas);
        //返回值的records是一个map集合
        List<LinkedHashMap<String, Object>> relationConfigList = (List<LinkedHashMap<String, Object>>)datas.get("records");
        log.error("=====RequestRuntimeHandleHook(提交到指定节点 getRelationConfigList)===relationConfigList{}",relationConfigList);
        return relationConfigList ;
    }
    
    
    @Override
    public Object handle(Object[] args) throws Exception {
        log.error("==RequestRuntimeHandleHook(提交到指定节点)===开始==" );
        Map<String, Object> result = new HashMap();
        // 参数1：eventType
        String eventType = (String) args[0];
        // 参数2：流程相关参数
        Map<String, Object> paramMap = (Map<String, Object>) args[1];
        long requestId = (long) paramMap.get("requestId");
        long workflowId = (long) paramMap.get("workflowId");
        long userId = (long) paramMap.get("userId");
        String operateType = (String) paramMap.get("operateType");
        Map<String, Object> baseInfo = (Map<String, Object>) paramMap.get("requestBaseInfo");
//        Map<String, Object> wfpPath = (Map<String, Object>) paramMap.get("wfpPath");
//        Map<String, Object> currentNode = (Map<String, Object>) paramMap.get("currentNode");
//        List<Map<String, Object>> nextNodeInfo = (List<Map<String, Object>>) paramMap.get("nextNodeInfo");
//        List<Map<String, Object>> currentNodeList = (List<Map<String, Object>>) paramMap.get("currentNodeList");
        // 参数3：流程操作请求参数；
        Map<String, Object> requestParam = (Map<String, Object>) args[2];
 
 
        String submitnodeidcus = "";
        if(operateType.equals("submit")){
            String tenantKey = Util.null2String(baseInfo.get("tenantKey"));
            boolean isSelectNextFlow = false;
            String userCurrentNodeId = Util.null2String(requestParam.get("userCurrentNodeId"));
            log.error("==RequestRuntimeHandleHook(提交到指定节点)===userCurrentNodeId:"+userCurrentNodeId );
            log.error("==RequestRuntimeHandleHook(提交到指定节点)===tenantKey:"+tenantKey );
            
            String sql = "select nodeids,fieldname from uf_wfsubmit_cus where workflowid='"+workflowId+"'";
            log.error("=====RequestRuntimeHandleHook(提交到指定节点)===sql:{}",sql);
            //返回值的records是一个map集合
            List<LinkedHashMap<String, Object>> relationConfigList = getRelationConfigList( sql , "weaver-ebuilder-form-service");
             log.error("=====RequestRuntimeHandleHook(提交到指定节点 uf_wfsubmit_cus)===relationConfigList:{}",relationConfigList);
            if(null!=relationConfigList) {
                List<String> nodeidsListcus = new ArrayList<>();
                String nodeids = "";
                String fieldname = "";
                for (int i = 0; i < relationConfigList.size(); i++) {
                    LinkedHashMap<String, Object> records = relationConfigList.get(i);
                    nodeids = Util.null2String( records.get("nodeids"));
                    fieldname = Util.null2String( records.get("fieldname"));
                }
                log.error("=====RequestRuntimeHandleHook(提交到指定节点)===nodeids:{}",nodeids);
                if (!nodeids.equals("")){
                    nodeidsListcus = Arrays.asList(nodeids.split(","));
                }
                log.error("=====RequestRuntimeHandleHook(提交到指定节点)===nodeidsListcus:{}===fieldname:{}",nodeidsListcus,fieldname);
                if ((nodeidsListcus.contains(userCurrentNodeId+"") || nodeidsListcus.size()==0) && !fieldname.equals("")){
                    
                    String relatekey="";
                    List<LinkedHashMap<String, Object>> relationConfigList22 = getRelationConfigList( "select relatekey from wfp_relateform where workflowid='"+workflowId+"'" , "weaver-workflow-list-service");
                    if(null!=relationConfigList22) {
                        for (int i = 0; i < relationConfigList22.size(); i++) {
                            LinkedHashMap<String, Object> records = relationConfigList22.get(i);
                            relatekey = Util.null2String(records.get("relatekey"));
                        }
                    }
                    log.error("=====RequestRuntimeHandleHook(提交到指定节点)=====relatekey:{}==",relatekey);
                    
                    // 查询到对应字段的fieldid
                    String tablename = "";
                    // 用户自定义表名查询
                    String sql2 = " select f2.table_name from form_table_field f,form_table f2,form_field f3  where  f.form_table_id=f2.id and f3.id=f.field_id and f.column_name='"+fieldname.toLowerCase()+"' and f3.form_id="+relatekey;
                    List<LinkedHashMap<String, Object>> relationConfigList2 = getRelationConfigList( sql2 , "weaver-workflow-list-service");
                    if(null!=relationConfigList2) {
                        for (int i = 0; i < relationConfigList2.size(); i++) {
                            LinkedHashMap<String, Object> records = relationConfigList2.get(i);
                            tablename = Util.null2String(records.get("table_name"));
                        }
                    }
                    log.error("==RequestRuntimeHandleHook(提交到指定节点form_table)==requestid:" + requestId + "===tablename:"+tablename +"===sql2:"+sql2);
                    
                    String form_value = "";
                    String sql3 = "select f.* from "+tablename+"  f" + "   inner join wfc_form_data f2 on f.id=f2.dataid  where f2.requestid="+requestId;
                    List<LinkedHashMap<String, Object>> relationConfigList3 = getRelationConfigList( sql3 , "weaver-workflow-list-service");
                    if(null!=relationConfigList3) {
                        for (int i = 0; i < relationConfigList3.size(); i++) {
                            LinkedHashMap<String, Object> records = relationConfigList3.get(i);
                            form_value = Util.null2String(records.get(fieldname));
                        }
                    }
                    log.error("==RequestRuntimeHandleHook(提交到指定节点 tablename)（获取字段值）=requestid:"+requestId+"==form_value:"+form_value+"===fieldname:"+fieldname +"==sql3:"+sql3);
                    
                    
                    String submitsqlcus = "select id from wfp_node where id ="+form_value+" and workflowid="+workflowId+" and tenant_key='"+tenantKey+"'";
                    List<LinkedHashMap<String, Object>> relationConfigList4 = getRelationConfigList( submitsqlcus , "weaver-workflow-list-service");
                    if(null!=relationConfigList4) {
                        for (int i = 0; i < relationConfigList4.size(); i++) {
                            LinkedHashMap<String, Object> records = relationConfigList4.get(i);
                            submitnodeidcus = Util.null2String(records.get("id"));
                        }
                    }
                    log.error("==RequestRuntimeHandleHook(提交到指定节点 wfp_node)=requestid:"+requestId+"=====submitnodeidcus:"+submitnodeidcus +"==submitsqlcus:"+submitsqlcus);
                }
            }
            
            if(!submitnodeidcus.equals("")&& Util.getLongValue(submitnodeidcus)>0 && !userCurrentNodeId.equals(submitnodeidcus)){
                result.put("submitToNodeId", submitnodeidcus);
            }
        }

        result.put("status", true);
        /**
         * 返回值为一个Map；
         * 1、当前返回两个字段；
         * 1.1 字段1：status：标识是否要正确执行下去；true：继续执行；false：阻断执行；
         * 1.2 字段2：msg：当status = false 时，需要返回msg作为精确提示信息；
         */
        result.put("msg", "");
        // 返回结果
        return result;
    }
}